// Home.js
import React, { useState , useEffect }  from 'react'; // 引入 useState
import { useNavigate,useMatch } from 'react-router-dom';
import Post from '../components/Post';
import Publish from '../components/Publish';
import Favorites from '../components/Favorites';
import FollowStats from '../components/FollowStats';
import PostButton from '../components/PostButton';  // 引入 PostButton 组件
import './Home.css';
import defaultAvatar from '../assets/images/默认头像.jpg';
import {getHome} from '../api/userApi';
import {getMyprofile} from '../api/userApi';

const Home = () => {
  const followingCount = 120;
  const followersCount = 1500;
  const navigate = useNavigate(); // 使用 useNavigate 来进行路由跳转
  const [isPublishing, setIsPublishing] = useState(false); // 添加状态管理
  const [isAvatarButtonVisible, setIsAvatarButtonVisible] = useState(true); // 头像和按钮的可见状态
  const [homeData, setHomeData] = useState(null); 
  const [myProfile, setMyProfile] = useState(null);  // 个人信息
  const match = useMatch("/home/:userId");
  const userId = match ? match.params.userId : null;

  // 获取数据
  useEffect(() => {
    if (userId) {
      // 如果有 userId，则调用 getHome 获取数据
      getHome(userId)
        .then((data) => {
          setHomeData(data);  // 设置获取到的数据
        })
        .catch((error) => {
          console.error('Error fetching home data:', error);
        });

      // 获取用户头像
      getMyprofile(userId)
        .then((data) => {
          setMyProfile(data);  // 设置获取到的数据
        })
        .catch((error) => {
          console.error('Error fetching my profile:', error);
        });
    }
  }, [userId]); // 当 userId 改变时重新执行该效果

  // 如果数据还在加载或没有数据，显示 loading 状态
  if (!homeData) {
    return <div>Loading...</div>;
  }

  if (!myProfile){
    return <div>Loading...</div>;
  }

  // 渲染博客数据
  const posts = homeData.map((blog) => ({
    userId:blog.userId,
    userImage: blog.userImage,
    blogImage: blog.blogImage,
    blogId: blog.blogId,
    interestId:blog.interestId,
    title: blog.name,
    author: blog.account,
    content: blog.description,
    time: blog.updateTime,
    likeCount: blog.likesCount,
    commentCount: blog.commentsCount,
    isLiked:blog.isLiked,
    isFollowed:blog.isFollowed,
    isCollected: blog.isCollected, 
  }));

  const avatarSrc = myProfile.image ? 'http://localhost:8080/'+ myProfile.image : defaultAvatar;



  // 处理发布按钮的点击事件
  const handlePostButtonClick = () => {
    setIsPublishing(true); // 点击后更新状态，显示 Publish
    setIsAvatarButtonVisible(false); // 隐藏头像和按钮
  };

  // 处理取消发布的事件
  const handleCancelButtonClick = () => {
    setIsPublishing(false); // 隐藏 Publish 组件
    setIsAvatarButtonVisible(true); // 显示头像和按钮
  };

  const handleAvatarClick = () => {
    navigate(`/personal/${userId}`); // 点击头像时跳转到个人页面
  };

  return (
    <div className="home">
      <div className="home-left">
        <div className="home-header">
          {isAvatarButtonVisible && (
            <>
              <img src={avatarSrc} alt="头像" className='avatar' onClick={handleAvatarClick} />
              <PostButton onClick={handlePostButtonClick} /> {/* 使用 PostButton 组件 */}
            </>
          )}
        </div>
        <div className="home-body">
          {isPublishing && <Publish onCancel={handleCancelButtonClick} />} {/* 根据状态决定是否显示 Publish 组件 */}
          <div className="posts-section">
            {posts.map((post) => (
              <Post key={post.blogId} post={post} />
            ))}
          </div>
        </div>
      </div>
      <div className="right-section">
        <Favorites />
        <FollowStats followingCount={followingCount} followersCount={followersCount} />
      </div>
    </div>
  );
};

export default Home;
